import { useGetFetchOptions, type Options } from './common'

/**
 * 响应式请求
 * 
 * @param key 请求key
 * @param url 请求url
 * @param options 请求设置
 */
export const useRefHttp = async <T>(key: string, url: string, options: Options = {}) => {
    options = useGetFetchOptions(options)
    options.key = key
    const { data, pending, refresh } = await useFetch<R<T>>(url, { ...options })
    /**
     * 状态码
     */
    const code = computed(() =>  data.value?.code ?? 500)
    /**
     * 消息
     */
    const msg = computed(() =>  data.value?.msg ?? '未知错误',)
    /**
     * 是否最后一页
     */
    const last = computed({
        get: () =>  data.value?.data?.last ?? true,
        set: val => data.value!.data.last = val
    })
    /**
     * 每页条数
     */
    const pageSize = computed({
        get: () =>  data.value?.data?.pageSize ?? 0,
        set: val => data.value!.data.pageSize = val
    })
    /**
     * 总条数
     */
    const total = computed({
        get: () => data.value?.data?.total ?? 0,
        set: val => data.value!.data.total = val
    })
    /**
     * 数据集合
     */
    const list = computed({
        get: () => data.value?.data?.list ?? [],
        set: val => data.value!.data.list = val
    })
    /**
     * 当前页码
     */
    const pageNum = computed({
        get: () => data.value?.data?.pageNum ?? 0,
        set: val => data.value!.data.pageNum = val
    })
    return { data, pending, refresh, code, msg, last, list, total, pageNum, pageSize }
}
/**
 * 响应式Get请求
 * 
 * @param key 请求key
 * @param url 请求url
 * @param options 请求设置
 */
export const useFetchRefGet = <T>(key: string, url: string, options: Options = {}) => {
    options.method = 'GET'
    return useRefHttp<T>(key, url, options)
}
/**
 * 响应式Post请求
 * 
 * @param key 请求key
 * @param url 请求url
 * @param options 请求设置
 */
export const useFetchRefPost = <T>(key: string, url: string, options: Options = {}) => {
    options.method = 'POST'
    return useRefHttp<T>(key, url, options)
}